package com.insight.modules.init;

import lombok.extern.slf4j.Slf4j;
import com.insight.common.constant.CacheConstant;
import com.insight.modules.system.service.ISysGatewayRouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @desc: 启动程序，初始化路由配置
 * @author: flyme
 */
@Slf4j
@Component
public class SystemInitListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {

    @Autowired
    private ISysGatewayRouteService sysGatewayRouteService;

    /**
     * 应用启动完成事件监听
     * 当Spring Boot应用准备好后触发，进行路由配置初始化
     *
     * @param applicationReadyEvent 应用启动完成事件
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        log.info("服务已启动，准备初始化路由配置 ###################");
        // 判断是否为Web环境启动的上下文
        if (applicationReadyEvent.getApplicationContext().getDisplayName()
                .indexOf("AnnotationConfigServletWebServerApplicationContext") > -1) {
            // 从数据库加载路由配置并写入Redis缓存
            sysGatewayRouteService.addRoute2Redis(CacheConstant.GATEWAY_ROUTES);
        }
    }

    /**
     * 指定监听器执行顺序，值越小优先级越高
     * @return 顺序值
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
